import React, { memo, useRef, useState,useCallback } from 'react'
import type { ComponentRef } from 'react'

import type { ReactNode } from 'react'
import { useAppSelector, shallowEqualApp } from '@/store'
import './style'
import { BannerControl, BannerLeft, BannerRight, BannerWrapper } from './style'
import { Carousel } from 'antd'
import classNames from 'classnames'
interface IProps {
  children?: ReactNode
}

const Recommend: React.FC<IProps> = () => {
  //ElementRef已被弃用
  // const carouselRef = useRef<ElementRef<typeof Carousel>>(null)
  const carouselRef = useRef<ComponentRef<typeof Carousel>>(null)

  const handlerPrev = () => {
    // console.log('上一张')
    carouselRef.current?.prev()
  }
  const handlerNext = () => {
    // console.log('下一张')
    carouselRef.current?.next()
  }

  const { banners } = useAppSelector(
    (state) => ({
      banners: state.recommend.banners
    }),
    shallowEqualApp
  )

    // 添加圆点点击处理函数
  const handleDotClick = (index: number) => {
    carouselRef.current?.goTo(index)
  }

  const [currentIndex, setCurrentIndex] = useState(0)
  const bgImage =
    banners[currentIndex] &&
    banners[currentIndex].imageUrl + '?imageView&blur=40x20'

  /** 事件监听的方法 */
  const bannerChange = useCallback((from: number, to: number) => {
    setTimeout(() => {
      setCurrentIndex(to)
    }, 0)
  }, [])

  return (
    <BannerWrapper $bgImage={bgImage}>
      <div className="banner wrap-v2">
        <BannerLeft>
          <Carousel dots={false} autoplay ref={carouselRef} effect="fade" beforeChange={bannerChange}>
            {banners.map((item) => (
              <div className="banner-item" key={item.imageUrl}>
                <img className="image" src={item.imageUrl} />
              </div>
            ))}
          </Carousel>
          <ul className="dots">
            {banners.map((item, index) => {
              return (
                <li key={item.imageUrl}>
                  <span
                    className={classNames('item', {
                      active: currentIndex === index
                    })}
                    onClick={() => handleDotClick(index)}
                  ></span>
                </li>
              )
            })}
          </ul>
        </BannerLeft>
        <BannerRight></BannerRight>
        <BannerControl>
          <button className="btn left" onClick={handlerPrev}></button>
          <button className="btn right" onClick={handlerNext}></button>
        </BannerControl>
      </div>
    </BannerWrapper>
  )
}

export default memo(Recommend)
